package com.authsphere.security.social.alipay;

import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.request.AuthAlipayRequest;
import me.zhyd.oauth.request.AuthRequest;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @program: AuthSphere
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/25 09:22
 **/
@Configuration
public class SocialAlipayConfiguration {
    private final String alipayPublicKey;
    private static final String AUTH_SPHERE_SECRET_KEY = "META-INF/authsphere/alipay_public_key.pk";

    public SocialAlipayConfiguration(ClassLoader classLoader) {
        URL url = Objects.nonNull(classLoader) ? classLoader.getResource(AUTH_SPHERE_SECRET_KEY)
                : ClassLoader.getSystemResource(AUTH_SPHERE_SECRET_KEY);
        if (Objects.nonNull(url)) {
            try (InputStream inputStream = url.openStream()) {
                this.alipayPublicKey = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
            } catch (IOException e) {
                throw new RuntimeException("Failed to read secret ket file.", e);
            }
        } else {
            throw new RuntimeException("Secret key file not found in resources.");
        }
    }
    public SocialAlipayConfiguration() {
        this(SocialAlipayConfiguration.class.getClassLoader());
    }

    @Bean
    @ConfigurationProperties(prefix = "authsphere.security.social.alipay")
    public AuthConfig alipayConfig() {
        return new AuthConfig();
    }

    @Bean(name = "alipay")
    public AuthRequest alipayAuthRequest(final AuthConfig alipayConfig) {
        return new AuthAlipayRequest(alipayConfig, alipayPublicKey);
    }
}
